package com.lyp.yangxixi.missionfragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.ajguan.library.EasyRefreshLayout;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.lyp.activitys.CarDayDetailsClueActivity;
import com.lyp.activitys.DectionDayDetailsClueActivity;
import com.lyp.activitys.IndoorDayDetailsClueActivity;
import com.lyp.adapters.MTodaytaskAdapter;
import com.lyp.jsonbean.LoginBean;
import com.lyp.jsonbean.MTodayBean;
import com.tjl.yangxixis.OriginalFragment;
import com.tjl.yangxixis.R;
import com.tjl.yangxixis.activity.MainActivity;
import com.tjl.yangxixis.api.YangxixiApi;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by Administrator on 2017/6/5.
 */
//今日任务
public class ToDayMissionFragment extends OriginalFragment{

    View v;
    private RecyclerView mRecyclerView;
    private MTodaytaskAdapter mAdapter;
    private LinearLayoutManager mLayoutManager;
    private List<MTodayBean.DataBean> mList = new ArrayList<>();
    private LoginBean.DataBean bean;
    private TextView mCounts;
    //定义一个页码为1
    int pages=1;
    private int mPosition;
    private EasyRefreshLayout mEasyRefreshLayout;

    public View createView(LayoutInflater inflater, ViewGroup container,
                           Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        v = inflater.inflate(R.layout.fragment_allmission, null,false);
        init();
        return v;
    }

    public void init(){
        bean = ((MainActivity) getActivity()).dataBean;
        mCounts = (TextView) v.findViewById(R.id.tv_counts);
        mRecyclerView = (RecyclerView) v.findViewById(R.id.grid_recycler);
        mLayoutManager = new LinearLayoutManager(getActivity());
        mRecyclerView.setLayoutManager(mLayoutManager);
        mAdapter = new MTodaytaskAdapter(mList);
        // 实例化 RecyclerView Adapter
        mRecyclerView.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(new MTodaytaskAdapter.MyItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                if(bean.getServer_select().equals("车内空气净化服务")){
                    Intent intentcar = new Intent(getActivity(),CarDayDetailsClueActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("databean",mList.get(position));
                    mPosition = position;
                    intentcar.putExtras(bundle);
                    startActivityForResult(intentcar, 0x2010);
                }
                else if(bean.getServer_select().equals("第三方检测服务")){
                    Intent intentdection = new Intent(getActivity(),DectionDayDetailsClueActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("databean",mList.get(position));
                    LogUtils.i("tag",mList.get(position).getO_id());
                    mPosition = position;
                    intentdection.putExtras(bundle);
                    startActivityForResult(intentdection, 0x2010);
                }
                else if(bean.getServer_select().equals("室内空气净化服务")){
                    Intent intentindoor = new Intent(getActivity(),IndoorDayDetailsClueActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("databean",mList.get(position));
                    mPosition = position;
                    intentindoor.putExtras(bundle);
                    startActivityForResult(intentindoor, 0x2010);
                }
            }
        });

        mEasyRefreshLayout = (EasyRefreshLayout) v.findViewById(R.id.easylayout);
        mEasyRefreshLayout.addEasyEvent(new EasyRefreshLayout.EasyEvent() {
            @Override
            public void onLoadMore() {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            todayTaskLoadMore(bean.getId(),pages);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mEasyRefreshLayout.loadMoreComplete();
                            }
                        });
                    }
                }).start();
            }

            @Override
            public void onRefreshing() {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        SystemClock.sleep(1000);
                        try {
                            todayTaskRefresh(bean.getId(),pages);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mEasyRefreshLayout.refreshComplete();
                            }
                        });
                    }
                }).start();
            }
        });
        try {
            todayTaskRefresh(bean.getId(),pages);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void lazyLoad() {
        // TODO Auto-generated method stub
    }

    //刷新
    public void todayTaskRefresh(String a_id,int page) throws IOException {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(YangxixiApi.APP_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        YangxixiApi github = retrofit.create(YangxixiApi.class);
        Call<MTodayBean> call = github.getMToday(a_id,page);
        call.enqueue(new Callback<MTodayBean>() {
            @Override
            public void onResponse(Call<MTodayBean> call, final Response<MTodayBean> response) {
                if (response.body().getResult()== 1 ) {
                    mCounts.setText(response.body().getCounts());
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mList.clear();
                            mList.addAll(response.body().getData());
                            mAdapter.notifyDataSetChanged();
                            if (response.body().getNext_page() > 0) {
                                pages++;
                            } else {
                                Toast.makeText(getActivity(),"没有更多数据了",Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                }else {
                    Toast.makeText(getActivity(),response.body().getMessage(),Toast.LENGTH_SHORT).show();
                }
            }
            @Override
            public void onFailure(Call<MTodayBean> call, Throwable t) {
               ToastUtils.showShort(t.getMessage());
            }
        });
    }

    //加载
    public void todayTaskLoadMore(String a_id,int page) throws IOException {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(YangxixiApi.APP_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        YangxixiApi github = retrofit.create(YangxixiApi.class);
        Call<MTodayBean> call = github.getMToday(a_id,page);
        call.enqueue(new Callback<MTodayBean>() {
            @Override
            public void onResponse(Call<MTodayBean> call, final Response<MTodayBean> response) {
                if (response.body().getResult()== 1 ) {
                    mCounts.setText(response.body().getCounts());
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mList.clear();
                            mList.addAll(response.body().getData());
                            mAdapter.notifyDataSetChanged();
                            mAdapter.notifyDataSetChanged();
                            if (pages >= 1) {
                                pages--;
                            } else {
                                Toast.makeText(getActivity(),"没有更多数据了",Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                }else {
                    ToastUtils.showShort(response.body().getMessage());
                }
            }
            @Override
            public void onFailure(Call<MTodayBean> call, Throwable t) {
                ToastUtils.showShort(t.getMessage());
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == getActivity().RESULT_OK){
            try {
                todayTaskRefresh(bean.getId(),pages);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        else if (resultCode == 20011){
            switch (requestCode) {
                case 0x2010:
                    mList.remove(mPosition);
                    mCounts.setText(mList.size()+"");
                    mAdapter.notifyDataSetChanged();
                    break;
            }
        }
    }

}
